var param = JSON.parse(localStorage.getItem('param'));
var addrId = ''; 
$(function(){
	//设置默认地址
	$('.chose-btn').on('click',function() {
		$(this).toggleClass('chose-sel');
	});
	init();
	initButton();
});
//初始化页面
function init(){
	if(param.addrId){
		addrId = param.addrId;
		$.ajax({
			type : "get",
			url : server_url
					+ 'rest/tea/user/addr/getAddrInfo.do?ran=' + Math.random(),
			dataType : 'json',
			async : true,
			data : {
				token : token,
				addrId:addrId
			},
			success : function(result) {
				if (result.retCode == '0000') {
					var addr = result.data;
					var userName = addr.userName;
					var userPhone = addr.userPhone;
					var userArea = addr.userArea;
					var userAddr =addr.userAddr;
					var isDefault = addr.isDefault;
					$('#linkMan').val(userName);
					$('#myPhone').val(userPhone);
					$('#expressArea').val(userArea);
					$('#userAddr').val(userAddr);
					if(isDefault=='1'){
						$('.chose-btn').addClass('chose-sel');
						$('.chose-btn').html('默认地址');
						$(".chose-btn").off();
					}
				} 
			}
		});
	}
}
//初始化绑定事件
function initButton(){
	//新增地址
	$('.address-btn-box').on('click',function(){
		var userName = $('#linkMan').val();
		var userPhone = $('#myPhone').val();
		var userArea = $('#expressArea').val();
		var userAddr = $('#userAddr').val();
		var isDefault = '0';
		if($('.chose-btn').hasClass('chose-sel')){
			isDefault = '1';
		}
		if(checkInput(userName,userPhone,userArea,userAddr)){
			$.ajax({
				type : "post",
				url : server_url
						+ 'rest/tea/user/addr/addUserAddr.do?ran=' + Math.random(),
				dataType : 'json',
				async : true,
				data : {
					token : token,
					userId:localStorage.getItem('userid'),
					userName:userName,
					userPhone:userPhone,
					userArea:userArea,
					userAddr:userAddr,
					isDefault:isDefault,
					addrId:addrId
				},
				success : function(result) {
					console.log(result);
					if (result.retCode == '0000') {
						localStorage.setItem('param',JSON.stringify(param));
						window.location = server_url + "addressList.do";
					} 
				}
			});
		}
	});
}
function checkInput(userName,userPhone,userArea,userAddr){
	if(!checkNull(userName,"请输入收货人")){
		return false;
	}
	if(!checkNull(userPhone,"请输入联系电话")){
		return false;
	}
	if(!checkNull(userArea,"请选择所属区域")){
		return false;
	}
	if(!checkNull(userAddr,"请输入具体地址")){
		return false;
	}
	return true;
	
}
//检查输入值是否为空
function checkNull(str, msg) {
	if (str) {
		if (str === '') {
			alert(msg);
			return false;
		}else{
			return true;
		}
	} else {
		alert(msg);
		return false;
	}
}

